|
|
|
|
|
|
|
Creating Calculated Fields |
|
|
|
|
|
|
|
|
The example in Listing C.1 has customer-order information consisting of the item ordered, quantity of the item, and the retail price. Suppose that you also want to access the total cost of the items. You can achieve this by using a calculated field in the SELECT statement. A calculated field can be the result of an arithmetic operation on numeric fields (for example, Price * Quantity) or the result of string operations on text fields (for example, Lastname & Firstname). For numeric fields, you can use any standard arithmetic operation (+, -, *, /, ^). For strings, you can use the concatenation operator (&). In addition, you can use Visual Basic functions to perform operations on the data in the fields (for example, you can use the MID$ function to extract a substring from a text field, the UCASE$ function to place text in uppercase letters, or the SQR function to calculate the square root of a number). Listing C.2 shows how some of these functions can be used in the SELECT statement. |
|
|
|
|
|
|
|
|
Listing C.2 TOTPRICE.TXTCreating a Variety of Calculated Fields with the SELECT Statement |
|
|
|
|
|
|
|
|
'***************************************
'Calculate the total price for the items
'***************************************
SELECT [Retail Items].Retail * Sales.Quantity FROM _
[Retail Items],Sales _
WHERE Sales.[Item Code]=[Retail Items].[Item Code]
'*****************************************************************
'Create a name field by concatenating the Lastname and
'Firstname fields
'*****************************************************************
SELECT Lastname & ', ' & Firstname FROM Customers
'*****************************************************************
'Create a customer ID using the first 3 letters of the Lastname
' and Firstname fields and make all letters uppercase.
'*****************************************************************
SELECT UCASE$(MID$(Lastname,1,3)) & UCASE$(MID$(Firstname,1,3)) _
FROM Customers
'***************************************************************
'Determine the square root of a number for use in a data report.
'***************************************************************
SELECT Datapoint, SQR(Datapoint) FROM Labdata |
|
|
|
|
|
|
|
|
In the listing, no field name is specified for the calculated field. The Query engine automatically assigns a name such as Expr1001 for the first calculated field. The next section, "Specifying Alternative Field Names," describes how you can specify a name for the field. |
|
|
|
|
|
|
|
|
Calculated fields are placed in the recordset as read-only fieldsthey can't be updated. In addition, if you update the base data used to create the field, the changes are not reflected in the calculated field. |
|
|
|
|
|